package top.jiangqiang.qianyi.data.handler;

import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import top.jiangqiang.qianyi.common.utils.JsonUtil;

/**
 * 数据库以字符串形式存储对象
 *
 * @author JiangQiang
 */
@Slf4j
@MappedTypes({Object.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class JacksonTypeHandler extends AbstractJsonTypeHandler<Object> {
    private final Class<?> type;

    public JacksonTypeHandler(Class<?> type) {
        super(type);
        if (log.isTraceEnabled()) {
            log.trace("JacksonTypeHandler(" + type + ")");
        }
        Assert.notNull(type, "Type argument cannot be null");
        this.type = type;
    }

    @Override
    public Object parse(String json) {
        return JsonUtil.parse(json, type);
    }

    @Override
    public String toJson(Object obj) {
        return JsonUtil.toJsonStr(obj);
    }

}

